package com.zhibang.config.security;

import com.alibaba.fastjson2.JSON;
import com.zhibang.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证异常处理类
 */
@Component
public class SecurityAuthenticationException implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // 设置响应JSON
        response.setContentType("application/json;charset=UTF-8");
        if(authException instanceof UsernameNotFoundException){
            Result<Object> r = Result.fail(401, authException.getMessage());
            response.getWriter().print(JSON.toJSONString(r));
        }else if(authException instanceof BadCredentialsException){
            Result<Object> r = Result.fail(401, "密码输入错误");
            response.getWriter().print(JSON.toJSONString(r));
        }else if(authException instanceof InsufficientAuthenticationException){
            Result<Object> r = Result.fail(401, "请重新登录");
            response.getWriter().print(JSON.toJSONString(r));
        }else{
            authException.printStackTrace();
            Result<Object> r = Result.fail(401, authException.getMessage());
            response.getWriter().print(JSON.toJSONString(r));
        }
    }
}
